package com.rambo.spm.common.controller;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Create by rambo on 2016/10/20
 * 抽象控制类 放置公共属性和方法
 **/
public abstract class BaseController {
    protected final static Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * form表单提交 Date类型数据绑定
     *
     * @param binder 日期绑定对象
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 设置成功响应代码
     *
     * @param modelMap 要返回的 modelMap
     */
    protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap) {
        return setSuccessModelMap(modelMap, null);
    }

    /**
     * 设置成功响应代码
     *
     * @param modelMap 要返回的 modelMap
     * @param data     modelMap 中要返回的数据
     */
    protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap, Object data) {
        return setModelMap(modelMap, HttpCode.OK, data);
    }

    /**
     * 设置响应代码
     *
     * @param modelMap 要返回的 modelMap
     * @param code     要返回的响应代码
     */
    protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code) {
        return setModelMap(modelMap, code, null);
    }

    /**
     * 设置响应代码
     *
     * @param modelMap 要返回的 modelMap
     * @param code     要返回的响应代码
     * @param data     modelMap 中要返回的数据
     */
    protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code, Object data) {
        Map<String, Object> map = Maps.newLinkedHashMap();
        map.putAll(modelMap);
        modelMap.clear();
        for (String key : map.keySet()) {
            if (!key.startsWith("org.springframework.validation.BindingResult") && !key.equals("void")) {
                modelMap.put(key, map.get(key));
            }
        }
        if (data != null) {
            modelMap.put("data", data);
        }
        modelMap.put("httpCode", code.getValue());
        modelMap.put("msg", code.getMsg());
        modelMap.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(modelMap);
    }
}